package com.lmxdawn.api.common.session;

import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.lmxdawn.api.common.autoconfigure.SessionProperties;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;
import java.util.Optional;

/**
 * Token 工具类
 *
 * @author jy
 * @since 2023-12-04 14:58
 */
public class TokenHelper {
    
    public static final String TOKEN_NAME = "Authorization";
    
    public static final String TOKEN_PREFIX = "Bearer";
    
    public static final String TOKEN_CONNECTOR_CHAT = " ";

    private TokenHelper() {

    }
    
    /**
     * 获取Token
     *
     * @param request
     * @return
     */
    public static String getTokenValueNotCut(HttpServletRequest request) {
        String tokenName = getTokenName();
        String token = request.getHeader(tokenName);
        if (StringUtils.isEmpty(token)) {
            token = request.getParameter(tokenName);
        }
        if (StringUtils.isEmpty(token)) {
            Cookie cookie = ServletUtil.getCookie(request, tokenName);
            if (Objects.nonNull(cookie)) {
                token = cookie.getValue();
            }
        }
        return token;
    }
    
    public static String getTokenValue(HttpServletRequest request) {
        String token = getTokenValueNotCut(request);
        if (StringUtils.isNotEmpty(token)) {
            String tokenPrefix = getTokenPrefix();
            if (StringUtils.isEmpty(tokenPrefix)) {
                return token;
            }
            if (token.startsWith(TOKEN_PREFIX + TOKEN_CONNECTOR_CHAT)) {
                token = token.substring(tokenPrefix.length() + TOKEN_CONNECTOR_CHAT.length());
            }
        }
        return token;
    }
    
    private static String getTokenName() {
        SessionProperties properties = SpringUtil.getBean(SessionProperties.class);
        return Optional.ofNullable(properties.getTokenName()).orElse(TOKEN_NAME);
    }
    
    private static String getTokenPrefix() {
        SessionProperties properties = SpringUtil.getBean(SessionProperties.class);
        return Optional.ofNullable(properties.getTokenPrefix()).orElse(TOKEN_PREFIX);
    }
    
}
